//公共业务处理文件
import db from './db.js'
import common from './common.js'
import mh from './messageHandler.js'
import apis from './apis.js'
import sock from './socket.js'

export default {
	// 删除消息
	async deleteMsg(msg) {
		await db.deleteMessage(msg.id);
		if (msg.messageType != 'Text') {
			if (msg.property && msg.property.image) {
				uni.removeSavedFile({
					filePath: msg.property.image
				})
			}
			uni.removeSavedFile({
				filePath: msg.content
			});
		}
	},
	// 清空消息
	async clearMsg(type, other) {
		const data = {
			type,
			other
		};
		const list = await db.getUntextMsg(data);
		//将文件全删掉
		list.forEach(content => {
			uni.removeSavedFile({
				filePath: content
			})
		});
		//将数据库记录删除
		await db.deleteMessageByOther(data);
		//移除掉最新消息中的记录
		common.removeNewMessage(data);
	},
	//登录
	async login(data) {
	    common.userName = data.UserName;
		common.token = data.Password; //设置token
		common.loginUser = data;
		await db.createTables();
		common.maxId = await db.getMaxId();
		await sock.initSocket(); //初始化websocket
		const [{
			Result: groups
		}, {
			Result: friends
		}, msgs] = await Promise.all([apis.getGroups(), apis.getFriends(), db.getNewestChatMessage()]); //获取群组、好友数据和最新聊天消息
		common.friends = friends;
		groups.forEach(group => {
			common.mappingGroupMembers(group.Item2); //映射群组成员
		});
		common.groups = groups.map(c => {
		    c.Item1.members = c.Item2;
		    return c.Item1;
		});
		const newMsgs = [];
		const avatars = common.friends.map(f => f.Avatar);
		avatars.push(common.loginUser.Avatar);
		await apis.BatchCheckDownloadAvatars(avatars); //批量下载头像
		msgs.forEach(msg => {
			const newMsg = common.createNewMessage(msg);
			if (newMsg) {
				newMsgs.push(newMsg);
			} else {
				db.deleteMessageByOther(msg);
			}
		});
		common.newMessage = newMsgs;
		common.connected = true;
		//登录
		uni.reLaunch({
			url: '/pages/message/list'
		});
	},
	//撤回消息
	async cancelMsg(item) {
		const [type, id, other, content] = item.Command.split(',');
		let msg = await db.getMessageByServerId(id, type);
		msg = Object.assign({
			other,
			type,
			id
		}, msg.shift());
		msg.msg = content;
		msg.time = item.CreateTime;
		mh.cancelMsg(msg);
	},
	//转发消息
	async transferMsgs(msgs, users) {
		msgs = common.deepClone(msgs, []);
		await Promise.all(msgs.map(msg =>
			new Promise(
				async res => {
					for (let user of users) {
						let tempData = common.deepClone(msg);
						tempData.other = user.id;
						tempData.senderId = common.loginUser.Id;
						tempData.time = common.serverTime;
						tempData.type = user.type;
						tempData.id = common.maxId;
						tempData.state = -1;
						if (msg.messageType == 'Video') {
							tempData.property.state = -1;
						}
						try {
							//如果不是文字则先复制一份文件
							if (msg.messageType != 'Text') {
								if (msg.messageType == 'Video') {
									tempData.property.state = -1;
									tempData.property.image = await new Promise((res, rej) => {
										uni.saveFile({
											tempFilePath: msg.property.image,
											success(e) {
												res(e.savedFilePath);
											},
											fail(e) {
												rej(e);
											}
										})
									});
								}
								tempData.content = await new Promise((res, rej) => {
									uni.saveFile({
										tempFilePath: msg.content,
										success(e) {
											res(e.savedFilePath);
										},
										fail(e) {
											rej(e);
										}
									})
								});
							}
						} catch (e) {
							console.log('文件复制出错', e);
							continue;
						}
						try {
							//没有服务ID的先处理
							if (!msg.serverId || msg.serverId < 1) {
								switch (msg.messageType) {
									case 'Text':
										tempData.serverId = msg.serverId = await mh.sendPGMessage(tempData);
										break;
										//是文件则先上传
									default:
										let result = null;
										const sendData = common.deepClone(tempData);
										//如果是视频并且缩略图都没上传则先上传缩略图
										if (msg.messageType == 'Video' && msg.property.state == -1) {
											result = await apis.uploadFile({
												filePath: tempData.property.image,
												receiverId: user.id,
												type: user.type == 1 ? 'p' : 'g'
											});
											sendData.property.image = result.Result;
											msg.property.state = 1;
										}
										result = await apis.uploadFile({
											filePath: tempData.content,
											receiverId: user.id,
											type: user.type == 1 ? 'p' : 'g'
										});
										sendData.content = result.Result;
										tempData.serverId = msg.serverId = await mh.sendPGMessage(sendData);
										break;
								}
								tempData.state = msg.state = 1;
							} else {
								const result = await mh.transferMsg(user.id, user.type, msg.serverId);
								tempData.serverId = parseInt(result.Data);
								tempData.state = 1;
							}
						} catch (e) {
							console.log('转发失败', e);
							tempData.state = 0;
						}
						try {
							db.insertNewMessage(tempData);
							common.newMessage = common.createNewMessage({
								    time: tempData.time,
								    id: tempData.id,
								    other: tempData.other,
								    type: tempData.type,
								    messageType: tempData.messageType,
								    content: tempData.content,
								    msgcount: 0
								});
						} catch (e) {
							console.log('转发成功，但是保存失败', e);
						}
					}
					res();
				})));
	}
}
